package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.constants.OrderConstants;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.order.Order;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.order.OrderElectronicInvoice;
import com.zbkj.common.model.order.OrderElectronicInvoiceItemDetail;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.OrderElectronicInvoiceRequest;
import com.zbkj.common.response.OrderElectronicInvoiceItemResponse;
import com.zbkj.common.response.OrderElectronicInvoiceResponse;
import com.zbkj.common.utils.CrmebUtil;
import com.zbkj.service.dao.OrderElectronicInvoiceDao;
import com.zbkj.service.dao.OrderElectronicInvoiceItemDetailDao;
import com.zbkj.service.service.MerchantService;
import com.zbkj.service.service.OrderDetailService;
import com.zbkj.service.service.OrderElectronicInvoiceService;
import com.zbkj.service.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单发票
 */
@Service
@Slf4j
public class OrderElectronicInvoiceServiceImpl extends ServiceImpl<OrderElectronicInvoiceDao, OrderElectronicInvoice>
        implements OrderElectronicInvoiceService {
    @Resource
    OrderElectronicInvoiceDao orderElectronicInvoiceDao;
    @Resource
    OrderElectronicInvoiceItemDetailDao orderElectronicInvoiceItemDetailDao;
    @Resource
    OrderService orderService;
    @Resource
    OrderDetailService orderDetailService;
    @Resource
    MerchantService merchantService;

    /**
     * 新增发票
     *
     * @return
     */
    public OrderElectronicInvoice add(OrderElectronicInvoice orderElectronicInvoice, List<Order> list) {
        orderElectronicInvoice.setIsCheck(0);
        Date d = new Date();
        orderElectronicInvoice.setNumber(CrmebUtil.getOrderNo(OrderConstants.ORDER_ELECTRONIC_INVOICE_PREFIX));
        orderElectronicInvoice.setOpenMergeInvoiceType(0);
        orderElectronicInvoice.setStatus(0);
        orderElectronicInvoice.setCreateTime(d);
        orderElectronicInvoice.setUpdateTime(d);
        if (CollectionUtil.isNotEmpty(list)) {
            for (Order order : list) {
                //每个订单号分配一个发票对象
                orderElectronicInvoice.setId(null);
                List<OrderElectronicInvoiceItemDetail> orderElectronicInvoiceItemDetailList = new ArrayList<>();
                List<OrderDetail> orderDetailList = orderDetailService.getByOrderNo(order.getOrderNo());
                for (OrderDetail orderDetail : orderDetailList) {
                    //批量插入商品信息
                    OrderElectronicInvoiceItemDetail orderElectronicInvoiceItemDetail = new OrderElectronicInvoiceItemDetail();
                    orderElectronicInvoiceItemDetail.setCreateTime(d);
                    orderElectronicInvoiceItemDetail.setUpdateTime(d);
                    orderElectronicInvoiceItemDetail.setElectronicInvoiceId(orderElectronicInvoice.getId());
                    orderElectronicInvoiceItemDetail.setOrderNumber(order.getOrderNo());
                    orderElectronicInvoiceItemDetail.setMerId(orderDetail.getMerId());
                    Merchant merchant = merchantService.getById(orderDetail.getMerId());
                    orderElectronicInvoiceItemDetail.setMerName(orderDetail.getMerName());
                    orderElectronicInvoiceItemDetail.setProductId(orderDetail.getProductId());
                    orderElectronicInvoiceItemDetail.setProductUrl(orderDetail.getImage());
                    orderElectronicInvoiceItemDetail.setProductName(orderDetail.getProductName());
                    orderElectronicInvoiceItemDetail.setSpecification(orderDetail.getSku());
                    orderElectronicInvoiceItemDetail.setUnitPrice(orderDetail.getPrice());
                    orderElectronicInvoiceItemDetail.setAmount(orderDetail.getPayPrice());
                    orderElectronicInvoiceItemDetail.setQuantity(new BigDecimal(orderDetail.getPayNum()));
                    if (merchant != null) {
                        orderElectronicInvoiceItemDetail.setMerName(merchant.getName());
                    }
                    orderElectronicInvoiceItemDetailList.add(orderElectronicInvoiceItemDetail);
                }
                //获取实际支付金额
                orderElectronicInvoice.setInvoiceAmount(order.getPayPrice());
                orderElectronicInvoiceDao.insert(orderElectronicInvoice);
                if (CollectionUtil.isNotEmpty(orderElectronicInvoiceItemDetailList)) {
                    orderElectronicInvoiceItemDetailList.forEach(item -> {
                        item.setElectronicInvoiceId(item.getElectronicInvoiceId());
                        orderElectronicInvoiceItemDetailDao.insert(item);
                    });
                }
                //设置订单为开票中
                orderService.update(new LambdaUpdateWrapper<Order>().eq(
                                Order::getOrderNo, order.getOrderNo())
                        .set(Order::getOpenInvoiceStatus, 1));

            }

        }


        return orderElectronicInvoice;
    }

    /**
     * 审核发票信息，提交pdf
     *
     * @param orderElectronicInvoiceRequest
     * @return
     */
    public OrderElectronicInvoiceRequest set(OrderElectronicInvoiceRequest orderElectronicInvoiceRequest) {
        OrderElectronicInvoice orderElectronicInvoice = new OrderElectronicInvoice();
        BeanUtils.copyProperties(orderElectronicInvoiceRequest, orderElectronicInvoice);
        Date d = new Date();
        orderElectronicInvoice.setUpdateTime(d);
        orderElectronicInvoiceDao.updateById(orderElectronicInvoice);
        return orderElectronicInvoiceRequest;
    }


    /**
     * 获取指定订单发票(单条)
     *
     * @param orderElectronicInvoiceRequest
     * @return
     */
    @Override
    public OrderElectronicInvoiceResponse getOrderNumber(OrderElectronicInvoiceRequest
                                                                 orderElectronicInvoiceRequest) {
        List<OrderElectronicInvoice> list = orderElectronicInvoiceDao.getOrderNumberList(orderElectronicInvoiceRequest.getOrderNumber());
        OrderElectronicInvoiceResponse orderElectronicInvoiceResponse = null;
        if (CollectionUtil.isNotEmpty(list)) {
            orderElectronicInvoiceResponse = get(list.get(0).getId());
        }
        return orderElectronicInvoiceResponse;
    }

    /**
     * 查询发票列表
     *
     * @param orderElectronicInvoiceRequest
     * @return
     */
    @Override
    public PageInfo<OrderElectronicInvoiceResponse> findByList(OrderElectronicInvoiceRequest
                                                                       orderElectronicInvoiceRequest) {
        List<Integer> idList = null;
        List<String> orderNumberList = orderElectronicInvoiceRequest.getOrderNumberList();
        if (StringUtils.isNotBlank(orderElectronicInvoiceRequest.getOrderNumber()) || CollectionUtil.isNotEmpty(orderNumberList)) {
            if (CollectionUtil.isEmpty(orderNumberList)) {
                orderNumberList = new ArrayList<>();
                orderNumberList.add("-1");
            }
            if (StringUtils.isNotBlank(orderElectronicInvoiceRequest.getOrderNumber())) {
                orderNumberList.add(orderElectronicInvoiceRequest.getOrderNumber());
            }

            idList = orderElectronicInvoiceItemDetailDao.selectList(new LambdaQueryWrapper<OrderElectronicInvoiceItemDetail>()
                            .select(OrderElectronicInvoiceItemDetail::getElectronicInvoiceId)
                            .in(OrderElectronicInvoiceItemDetail::getOrderNumber, orderNumberList))
                    .stream()
                    .map(detail -> detail.getElectronicInvoiceId())
                    .collect(Collectors.toList());
            if (CollectionUtil.isEmpty(idList)) {
                //无搜索内容
                idList = new ArrayList<>();
                idList.add(-1);
            }
        }
        if (orderElectronicInvoiceRequest.getMerId() != null) {
            idList = orderElectronicInvoiceItemDetailDao.selectList(new LambdaQueryWrapper<OrderElectronicInvoiceItemDetail>()
                            .select(OrderElectronicInvoiceItemDetail::getElectronicInvoiceId)
                            .eq(OrderElectronicInvoiceItemDetail::getMerId, orderElectronicInvoiceRequest.getMerId()))
                    .stream()
                    .map(detail -> detail.getElectronicInvoiceId())
                    .collect(Collectors.toList());
            if (CollectionUtil.isEmpty(idList)) {
                //无搜索内容
                idList = new ArrayList<>();
                idList.add(-1);
            }
        }

        Page<OrderElectronicInvoice> page = PageHelper.startPage(orderElectronicInvoiceRequest.getPage(), orderElectronicInvoiceRequest.getLimit());
        LambdaQueryWrapper<OrderElectronicInvoice> lqw = Wrappers.lambdaQuery();
        //开票类型
        lqw.eq(orderElectronicInvoiceRequest.getIsOpenMergeInvoiceType() != null,
                OrderElectronicInvoice::getIsOpenMergeInvoiceType, orderElectronicInvoiceRequest.getIsOpenMergeInvoiceType());
        //开票类型
        lqw.eq(orderElectronicInvoiceRequest.getOpenMergeInvoiceType() != null,
                OrderElectronicInvoice::getOpenMergeInvoiceType, orderElectronicInvoiceRequest.getOpenMergeInvoiceType());
        //发票状态
        lqw.eq(orderElectronicInvoiceRequest.getStatus() != null,
                OrderElectronicInvoice::getStatus, orderElectronicInvoiceRequest.getStatus());
        //发票类型
        lqw.eq(orderElectronicInvoiceRequest.getInvoiceType() != null,
                OrderElectronicInvoice::getInvoiceType, orderElectronicInvoiceRequest.getInvoiceType());
        //开票号
        lqw.like(StringUtils.isNotBlank(orderElectronicInvoiceRequest.getNumber()),
                OrderElectronicInvoice::getNumber, orderElectronicInvoiceRequest.getNumber());
        // 开票状态
        lqw.eq(orderElectronicInvoiceRequest.getIsCheck() != null,
                OrderElectronicInvoice::getIsCheck, orderElectronicInvoiceRequest.getIsCheck());
//        lqw.eq(orderElectronicInvoiceRequest.getOrderNumber() == null,
//                OrderElectronicInvoice::getOrderNumber, orderElectronicInvoiceRequest.getOrderNumber());
        //抬头
        lqw.like(StringUtils.isNotBlank(orderElectronicInvoiceRequest.getInvoiceTitle()),
                OrderElectronicInvoice::getInvoiceTitle, orderElectronicInvoiceRequest.getInvoiceTitle());
        lqw.in(CollectionUtil.isNotEmpty(idList), OrderElectronicInvoice::getId, idList);

        lqw.orderByDesc(OrderElectronicInvoice::getCreateTime);
        List<OrderElectronicInvoice> list = orderElectronicInvoiceDao.selectList(lqw);
        List<OrderElectronicInvoiceResponse> responseList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (OrderElectronicInvoice orderElectronicInvoice : list) {
                responseList.add(get(orderElectronicInvoice.getId()));
            }
        }
        return CommonPage.copyPageInfo(page, responseList);
    }

    /**
     * 发票拆分
     */
    @Override
    public void saveOrderInvoiceSplitting(String orderNumber, List<Order> orderList) {
        log.info("订单号：{} 开始发票拆分", orderNumber);
        List<OrderElectronicInvoice> list = orderElectronicInvoiceDao.getOrderNumberList(orderNumber);
        if (CollectionUtil.isNotEmpty(list) && list.get(0) != null) {
            OrderElectronicInvoice orderElectronicInvoice = list.get(0);
            Integer id = orderElectronicInvoice.getId();
            orderElectronicInvoice.setId(null);
            add(orderElectronicInvoice, orderList);
            //删除以平台订单创建的发票信息
            orderElectronicInvoiceDao.deleteById(id);
            orderElectronicInvoiceItemDetailDao.delete(new LambdaQueryWrapper<OrderElectronicInvoiceItemDetail>()
                    .eq(OrderElectronicInvoiceItemDetail::getElectronicInvoiceId, id)
            );
        }

    }

    @Override
    public com.baomidou.mybatisplus.extension.plugins.pagination.Page<OrderElectronicInvoiceResponse> getList(OrderElectronicInvoiceRequest orderElectronicInvoiceRequest) {
        return null;
    }


    /**
     * 查询指定订单的发票列表
     *
     * @param orderElectronicInvoiceRequest
     * @return
     */
    public PageInfo<OrderElectronicInvoiceResponse> getOrderNumberList(OrderElectronicInvoiceRequest
                                                                               orderElectronicInvoiceRequest) {
        Page<OrderElectronicInvoice> page = PageHelper.startPage(orderElectronicInvoiceRequest.getPage(), orderElectronicInvoiceRequest.getLimit());
        List<OrderElectronicInvoice> list = orderElectronicInvoiceDao.getOrderNumberList(orderElectronicInvoiceRequest.getOrderNumber());
        List<OrderElectronicInvoiceResponse> responseList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (OrderElectronicInvoice orderElectronicInvoice : list) {
                responseList.add(get(orderElectronicInvoice.getId()));
            }
        }
        return CommonPage.copyPageInfo(page, responseList);
    }


    /**
     * 获取指定发票
     *
     * @param id
     * @return
     */
    @Override
    public OrderElectronicInvoiceResponse get(Integer id) {
        OrderElectronicInvoiceResponse orderElectronicInvoiceResponse = new OrderElectronicInvoiceResponse();
        OrderElectronicInvoice orderElectronicInvoice = orderElectronicInvoiceDao.selectById(id);
        BeanUtils.copyProperties(orderElectronicInvoice, orderElectronicInvoiceResponse);
        LambdaQueryWrapper<OrderElectronicInvoiceItemDetail> lqw = Wrappers.lambdaQuery();
        lqw.eq(OrderElectronicInvoiceItemDetail::getElectronicInvoiceId, id);
        lqw.orderByDesc(OrderElectronicInvoiceItemDetail::getCreateTime);
        List<OrderElectronicInvoiceItemDetail> list = orderElectronicInvoiceItemDetailDao.selectList(lqw);
        if (CollectionUtil.isNotEmpty(list)) {
            // 1. 按订单号分组：Map<订单号, 该订单下的商品列表>
            Map<String, List<OrderElectronicInvoiceItemDetail>> groupedByOrderNumber = list.stream()
                    .collect(Collectors.groupingBy(OrderElectronicInvoiceItemDetail::getOrderNumber));
            List<OrderElectronicInvoiceItemResponse> itemResponseList = new ArrayList<>();
            //根据订单号聚合商品
            for (String orderNumber : groupedByOrderNumber.keySet()) {
                OrderElectronicInvoiceItemResponse itemResponse = new OrderElectronicInvoiceItemResponse();
                List<OrderElectronicInvoiceItemDetail> itemList = groupedByOrderNumber.get(orderNumber);
                itemResponse.setTotal(itemList.size());
                itemResponse.setList(itemList);
                itemResponse.setOrderNumber(orderNumber);
                itemResponse.setMerId(itemList.get(0).getMerId());
                itemResponse.setMerName(itemList.get(0).getMerName());
                itemResponseList.add(itemResponse);
            }
            orderElectronicInvoiceResponse.setItemList(itemResponseList);
        }
        return orderElectronicInvoiceResponse;
    }
}
